package org.stvd.core.process;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.stvd.core.web.IOUtil;

import jxl.common.Logger;

public class InputStreamWatchThread extends Thread {
    private final Process process;
    private boolean over = false;
    private String message = "";
    private String filename = "";
    private String filepath = "";
    private static final Logger logger = Logger.getLogger(InputStreamWatchThread.class);

    public InputStreamWatchThread(Process p) {
        process = p;
        over = false;
    }

    public InputStreamWatchThread(Process p, String filepath, String filename) {
        process = p;
        over = false;
        this.filepath = filepath;
        this.filename = filename;
    }

    public void run() {
        BufferedReader br = null;
        try {
            if (process == null) {
                logger.info("process为null,InputStreamWatchThread无法处理文件转换");
                message += "process为null,InputStreamWatchThread无法处理文件转换\n";
                return;
            }

            logger.info("输出InputStreamWatchThread信息:");
            message += "输出InputStreamWatchThread信息:\n";

            br = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
            // BufferedReader br = new BufferedReader(
            // new InputStreamReader(process.getInputStream()));
            while (true) {
                if (over) {
                    logger.info("InputStreamWatchThread处理完成！");
                    message += "InputStreamWatchThread处理完成！\n";
                    break;
                }
                String temp = br.readLine();
                while (temp != null) {
                    logger.info(temp);
                    message += temp + "\n";
                    temp = br.readLine();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("InputStreamWatchThread发生异常" + e.getMessage());
            message += "InputStreamWatchThread发生异常" + e.getMessage() + "\n";
        } finally {
            try {
                if (br != null) {
                    br.close();
                    br = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            if (!"".equals(message.trim()) && !"".equals(filepath) && !"".equals(filename)) {
                logger.info("InputStreamWatchThread信息保存文件!");
                IOUtil.saveFile(filepath, filename, message, true);
            }
        } catch (Exception e) { }
    }

    public void setOver(boolean over) {
        this.over = over;
    }
}